package org.xqp.basic.util;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.xqp.user.domain.Logininfo;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

/**
 * 从请求头中获取用户信息的工具类
 */

public class LoginContextUtil {

    public static Logininfo getLoginContext(){
        //请求: RequestContextHolder是SpringMVC中的一个请求上下文工具，里面有ServletRequestAttributes
        //而：ServletRequestAttributes里面有请求对象
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        //拿到请求对象
        HttpServletRequest request = requestAttributes.getRequest();

        return getLoginContext(request);
    }
    public static Logininfo getLoginContext(HttpServletRequest request){
        // 获取请求头中的token
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
        // 不通过注释 通过代码 获取spring容器  webApplicationContext就是spring容器
            WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());

            //通过spring容器获取redisTemplate对象
            RedisTemplate redisTemplate = (RedisTemplate)webApplicationContext.getBean("redisTemplate");
            // 根据token获取储存在redis中的用户登录信息logininfo
            Logininfo logininfo = (Logininfo)redisTemplate.opsForValue().get(token);
            if (logininfo!=null){
                return logininfo;
            }
        }
        return null;
    }
}
